package 多线程10_ThreadLocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName: TestThreadLocal01
 * @Author: AllenSun
 * @Date: 2022/4/1 上午1:07
 */
public class TestThreadLocal01  {
    ThreadLocal<String> threadLocal = new ThreadLocal<>();

    private String content;
    private String contentSynchronized;

    public String getContent() {
        return content;
    }

    public String getContentSynchronized() {
        return contentSynchronized;
    }

    public void setContentSynchronized(String contentSynchronized) {
        this.contentSynchronized = contentSynchronized;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getContentTL() {
        String s=threadLocal.get();
        return s;
    }

    public void setContentTL(String content) {
        threadLocal.set(content);
    }


    public static void main(String[] args) {

        TestThreadLocal01 threadLocal01 = new TestThreadLocal01();

        ExecutorService es = Executors.newFixedThreadPool(200);
        for (int i=0;i<5;i++) {
            es.submit(new Runnable() {
                @Override
                public void run() {
                    /*//没有使用ThreadLocal设置的变量
                    threadLocal01.setContent(Thread.currentThread().getName()+"的数据");
                    System.out.println("---------------");
                    System.out.println(Thread.currentThread().getName()+"--->"+threadLocal01.getContent());*/
                    //使用ThreadLocal设置的变量
                    threadLocal01.setContentTL(Thread.currentThread().getName()+"的ThreadLocal数据");
                    System.out.println("---------------");
                    System.out.println(Thread.currentThread().getName()+"--->"+threadLocal01.getContentTL());
                    /*//使用sync锁实现绑定(可以实现，但是加锁以后只能排队访问，降低了并发性)
                    synchronized (this.getClass()) {
                        threadLocal01.setContentSynchronized(Thread.currentThread().getName()+"的synchronized数据");
                        System.out.println("---------------");
                        System.out.println(Thread.currentThread().getName()+"--->"+threadLocal01.getContentSynchronized());

                    }*/
                }
            });
        }

    }
}
